package com.shbaiche.bifenba.ui.video;

import android.annotation.SuppressLint;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;

import com.google.gson.Gson;
import com.shbaiche.bifenba.R;
import com.shbaiche.bifenba.adapter.video.VideoAdapter;
import com.shbaiche.bifenba.model.base.TransMessage;
import com.shbaiche.bifenba.model.video.ArticleGroupListMessage;
import com.shbaiche.bifenba.model.video.ArticleGroupVo;
import com.shbaiche.bifenba.model.video.ArticleListMessage;
import com.shbaiche.bifenba.model.video.ArticleVo;
import com.shbaiche.bifenba.net.JsonCallback;
import com.shbaiche.bifenba.net.NetApi;
import com.shbaiche.bifenba.ui.base.BaseFragment;
import com.shbaiche.bifenba.util.StringUtil;
import com.shbaiche.bifenba.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.droidlover.xdroidbase.base.XFragmentAdapter;
import cn.droidlover.xstatecontroller.XStateController;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard;
import okhttp3.Call;

/**
 * Created by wanglei on 2016/12/10.
 */

@SuppressLint("ValidFragment")
public class VideoTeamFragment extends BaseFragment {
    private String videoUrl = "http://gslb.miaopai.com/stream/ed5HCfnhovu3tyIQAiv60Q__.mp4";
    @BindView(R.id.video_lv)
    ListView listView;
    private ArrayList<String> datas;
    private JCVideoPlayerStandard currPlayer;
    private VideoAdapter adapter;
    private AbsListView.OnScrollListener onScrollListener;
    private int firstVisible;//当前第一个可见的item
    private int visibleCount;//当前可见的item个数

    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.contentLayout)
    XStateController contentLayout;

    private Long typeId;

    private int index = 0;

    public VideoTeamFragment() {

    }


    public static VideoTeamFragment newInstance() {
        return new VideoTeamFragment();
    }


    @Override
    public void initData(Bundle savedInstanceState) {
        if(savedInstanceState!=null && savedInstanceState.containsKey("data")){
            typeId = savedInstanceState.getLong("data");
        }else{
            typeId = getArguments().getLong("data");
        }




        initListener();

        initRefreshLayout();

        initContentLayout();

        contentLayout.showLoading();

        load();
    }

    private void load() {
        ArticleListMessage msg = new ArticleListMessage();
//        msg.setType(ArticleGroupVo.Type.VIDEO);
        msg.setGroupId(typeId);
        msg.setPageIndex(index);
        msg.setPageSize(10);

        NetApi.videoList(msg, new JsonCallback<TransMessage>() {

            @Override
            public void onFail(Call call, Exception e, int id) {
                contentLayout.showContent();
                if (swipeRefreshLayout != null)
                    swipeRefreshLayout.setRefreshing(false);
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                contentLayout.showContent();
                ToastUtil.show("onFail" + e.getMessage());
                if (swipeRefreshLayout != null)
                    swipeRefreshLayout.setRefreshing(false);
            }

            @Override
            public void onResponse(TransMessage response, int id) {

                if (swipeRefreshLayout != null)
                    swipeRefreshLayout.setRefreshing(false);
                contentLayout.showContent();

                Gson gson = new Gson();
                ArticleListMessage msg = gson.fromJson(response.getMessage(), ArticleListMessage.class);

                if (StringUtil.equalsIgnoreCase(TransMessage.SuccessCode, msg.getCode())) {
                    List<ArticleVo> list = msg.getList();

                    List<String> suData = new ArrayList<>();
                    for (int i = 0; i < list.size(); i++) {
                        ArticleVo vo = list.get(i);
                        if (vo != null && !TextUtils.isEmpty(vo.getVideoUrl())) {
                            suData.add(vo.getVideoUrl());
                        }
                    }

                    adapter = new VideoAdapter(getActivity(), suData, list, R.layout.adapter_video_item);
                    listView.setAdapter(adapter);

                } else {


                }

            }
        });
    }

    private void initRefreshLayout() {
        swipeRefreshLayout.setColorSchemeResources(
                android.R.color.holo_blue_light,
                android.R.color.holo_red_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_green_light);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                index = 0;
                load();
            }
        });

    }

    private void initContentLayout() {
        contentLayout.loadingView(View.inflate(getActivity(), R.layout.view_loading, null));
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_video;
    }


    /**
     * 滑动监听
     */
    private void initListener() {
        onScrollListener = new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

                switch (scrollState) {
                    case AbsListView.OnScrollListener.SCROLL_STATE_FLING:
                        break;

                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                        //滑动停止自动播放视频
                        autoPlayVideo(view);
                        break;

                    case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
                        break;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (firstVisible == firstVisibleItem) {
                    return;
                }

                firstVisible = firstVisibleItem;
                visibleCount = visibleItemCount;
            }
        };

        listView.setOnScrollListener(onScrollListener);
    }

    /**
     * 滑动停止自动播放视频
     */
    private void autoPlayVideo(AbsListView view) {

        for (int i = 0; i < visibleCount; i++) {
            if (view != null && view.getChildAt(i) != null && view.getChildAt(i).findViewById(R.id.player_list_video) != null) {
                currPlayer = (JCVideoPlayerStandard) view.getChildAt(i).findViewById(R.id.player_list_video);
                Rect rect = new Rect();
                //获取当前view 的 位置
                currPlayer.getLocalVisibleRect(rect);
                int videoheight = currPlayer.getHeight();
                if (rect.top == 0 && rect.bottom == videoheight) {
                    if (currPlayer.currentState == JCVideoPlayer.CURRENT_STATE_NORMAL
                            || currPlayer.currentState == JCVideoPlayer.CURRENT_STATE_ERROR) {
                        currPlayer.startButton.performClick();
                    }
                    return;
                }
            }
        }
        //释放其他视频资源
        JCVideoPlayer.releaseAllVideos();
    }

//    @Override
//    public void onBackPressed() {
//        if (JCVideoPlayer.backPress()) {
//            return;
//        }
//        super.onBackPressed();
//    }


    @Override
    public void onPause() {
        super.onPause();
        JCVideoPlayer.releaseAllVideos();
    }
}
